<template>
    <div class="framework1">
        <!--    全部表格-->
        <div class="framework2">

            <!--      上半部分表格-->
            <div>

                <div class="header">数据字典->法律条款</div>

                <div class="button_group">
                    <el-button type="primary" icon="DocumentAdd" v-if="permissionIsShow.add"
                        @click="addTerms">新增条款</el-button>
                    <el-select v-model="searchLawType" clearable placeholder="搜索法律类型"
                        style="width: 200px;margin-left: 10px;margin-right: 10px">
                        <el-option v-for="type in uniquelawTypes" :key="type" :label="type" :value="type" />
                    </el-select>
                    <el-select v-model="searchLawName" clearable placeholder="搜索法律名称"
                        style="width: 200px;margin-right: 10px">
                        <el-option v-for="low in filteredLowsByType(searchLawType)" :key="low.id" :label="low.name"
                            :value="low.name" />
                    </el-select>
                    <!-- <el-input v-model="searchLawType" placeholder="搜索法律类型"
                        style="width: 200px;margin-left: 10px;margin-right: 10px" clearable></el-input>
                    <el-input v-model="searchLawName" placeholder="搜索法律名称" style="width: 200px;margin-right: 10px"
                        clearable></el-input> -->
                    <el-input v-model="searchArticle" placeholder="搜索条" style="width: 100px;margin-right: 10px"
                        clearable></el-input>
                    <el-input v-model="searchParagraph" placeholder="搜索款" style="width: 100px;margin-right: 10px"
                        clearable></el-input>
                    <el-input v-model="searchSubparagraph" placeholder="搜索项" style="width: 100px;margin-right: 10px"
                        clearable></el-input>
                    <el-input v-model="searchItem" placeholder="搜索目" style="width: 100px;margin-right: 10px"
                        clearable></el-input>

                    <el-button type="primary" icon="Search" @click="searchTerms()">搜索</el-button>
                </div>
                <div style="height: calc(100vh - 134px)">
                    <el-table :data="TermsList" :header-cell-style="{ background: '#f4f3f9' }" highlight-current-row
                        style="width:100%; height: calc(100% - 68px); background:#f4f3f9" border>
                        <el-table-column align="center" prop="lawType" label="法律类型" width="200"></el-table-column>
                        <el-table-column align="center" prop="lawName" label="法律名称" width="350"></el-table-column>
                        <el-table-column align="center" prop="article" label="条" width="150"></el-table-column>
                        <el-table-column align="center" prop="paragraph" label="款" width="150"></el-table-column>
                        <el-table-column align="center" prop="subparagraph" label="项" width="150"></el-table-column>
                        <el-table-column align="center" prop="item" label="目" width="150"></el-table-column>
                        <el-table-column align="center" prop="content" label="内容" width="350"></el-table-column>

                        <el-table-column align="center" prop="operate" label="操作" width="200" fixed="right"
                            v-if="permissionIsShow.edit || permissionIsShow.delete">
                            <template v-slot="scope">
                                <el-button type="primary" size="small" icon="Edit" v-if="permissionIsShow.edit"
                                    @click.native.stop="editRoleData(scope.row)">修改</el-button>
                                <el-button type="danger" size="small" icon="Delete" v-if="permissionIsShow.delete"
                                    @click.native.stop="deleteRoleData(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--      分页1-->
                    <div class="footer">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :page-sizes="[5, 10, 20]" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper" :total="total">
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>
        <!-- 新增/编辑 弹窗 -->
        <el-dialog v-model="dialogFormVisible" :close-on-click-modal="false" :title="isEdit ? '修改' : '新增'"
            :before-close="closeAddTerms" width="900px">
            <el-form>
                <el-form-item v-model="inputTermsObject" :key="index">
                    <span>法律类型：</span>
                    <el-select v-model="inputTermsObject.lawType" filterable allow-create clearable
                        placeholder="例：【行政法规】" style="width: 100%;"
                        @change="(val) => handlelawTypeChange(inputTermsObject, val)"
                        @blur="handlelawTypeBlur(inputTermsObject, $event)"
                        @clear="clearLawsFields(inputTermsObject, 'type')">
                        <el-option v-for="type in uniquelawTypes" :key="type" :label="type" :value="type" />
                    </el-select>
                    <span style="margin-top: 10px;">法律名称：</span>
                    <el-select v-model="inputTermsObject.lawName" filterable allow-create clearable
                        placeholder="例：《城市市容和环境卫生管理条例》" style="width: 100%;"
                        @change="(val) => handlelawNameChange(inputTermsObject, val)"
                        @blur="handlelawNameBlur(inputTermsObject, $event)" :disabled="!inputTermsObject.lawType"
                        @clear="clearLawsFields(inputTermsObject, null)">
                        <el-option v-for="low in filteredLowsByType(inputTermsObject.lawType)" :key="low.id"
                            :label="low.name" :value="low.name" />
                    </el-select>
                    <span style="margin-top: 10px;">第几条：</span>
                    <el-input type="textarea" v-model="inputTermsObject.article" placeholder="请输入第几条"
                        :disabled="isArticleEditable(inputTermsObject)" />
                    <span style="margin-top: 10px;">第几款：</span>
                    <el-input type="textarea" v-model="inputTermsObject.paragraph" placeholder="请输入第几款"
                        :disabled="isParagraphEditable(inputTermsObject)" />
                    <span style="margin-top: 10px;">第几项：</span>
                    <el-input type="textarea" v-model="inputTermsObject.subparagraph" placeholder="请输入第几项"
                        :disabled="isSubparagraphEditable(inputTermsObject)" />
                    <span style="margin-top: 10px;">第几目：</span>
                    <el-input type="textarea" v-model="inputTermsObject.item" placeholder="请输入第几目"
                        :disabled="isItemEditable(inputTermsObject)" />
                    <span style="margin-top: 10px;">条款内容：</span>
                    <el-input type="textarea" v-model="inputTermsObject.content" placeholder="请输入条款内容"
                        :disabled="isContentEditable(inputTermsObject)" />


                    <!-- <el-select v-model="inputTermsObject.article" filterable allow-create clearable placeholder="条"
                        style="width: 100px; margin-right: 10px"
                        @change="(val) => handleArticleChange(inputTermsObject, val)"
                        @blur="handleArticleBlur(inputTermsObject, $event)"
                        :disabled="isArticleEditable(inputTermsObject)"
                        @clear="clearDependentFields(inputTermsObject, 1)">
                        <el-option v-for="article in articleList" :key="article" :label="article" :value="article" />
                    </el-select>
                    <el-select v-model="inputTermsObject.paragraph" filterable allow-create clearable placeholder="款"
                        style="width: 100px; margin-right: 10px"
                        @change="(val) => handleParagraphChange(inputTermsObject, val)"
                        @blur="handleParagraphBlur(inputTermsObject, $event)"
                        :disabled="isParagraphEditable(inputTermsObject)"
                        @clear="clearDependentFields(inputTermsObject, 2)">
                        <el-option v-for="paragraph in paragraphList" :key="paragraph" :label="paragraph"
                            :value="paragraph" />
                    </el-select>
                    <el-select v-model="inputTermsObject.subparagraph" filterable allow-create clearable placeholder="项"
                        style="width: 100px; margin-right: 10px"
                        @change="(val) => handleSubparagraphChange(inputTermsObject, val)"
                        @blur="handleSubparagraphBlur(inputTermsObject, $event)"
                        :disabled="isSubparagraphEditable(inputTermsObject)"
                        @clear="clearDependentFields(inputTermsObject, 3)">
                        <el-option v-for="subparagraph in subparagraphList" :key="subparagraph" :label="subparagraph"
                            :value="subparagraph" />
                    </el-select>
                    <el-select v-model="inputTermsObject.item" filterable allow-create clearable placeholder="目"
                        style="width: 100px; margin-right: 10px"
                        @change="(val) => handleItemChange(inputTermsObject, val)"
                        @blur="handleItemBlur(inputTermsObject, $event)" :disabled="isItemEditable(inputTermsObject)"
                        @clear="clearDependentFields(inputTermsObject, 4)">
                        <el-option v-for="item in itemList" :key="item.id" :label="item.item" :value="item.item" />
                    </el-select> -->

                </el-form-item>
            </el-form>


            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeAddTerms()">取消</el-button>
                    <el-button type="primary" @click="saveTerms()">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

</template>

<script>
import request from "@/utils/request";
export default {
    name: "Terms",
    data() {
        return {
            // 搜索匹配
            searchLawType: "",
            searchLawName: "",
            searchArticle: "",
            searchParagraph: "",
            searchSubparagraph: "",
            searchItem: "",

            TermsList: [], // 违法行为列表
            lowsList: [], // 法律列表
            articleList: [], // 第几条列表
            paragraphList: [], // 第几款列表
            subparagraphList: [], // 第几项列表
            itemList: [], // 第几目列表

            total: 0,
            pageSize: 10,
            pageNum: 1,

            dialogFormVisible: false, //新增弹窗控制
            isEdit: false, // 编辑标志
            inputTermsObject: {
                id: null,
                lawsId: null, // 法律ID
                article: null, // 第几条
                paragraph: null, // 第几款
                subparagraph: null, // 第几项
                item: null, // 第几目
                lawName: null, // 法律名称
                lawType: null, // 法律类型
                content: null, // 条款内容
            },
            // 登录用户信息
            loginUserInfo: {
                id: '',
                responsibleScope: '', //查询范围
                roleLevel: '', //角色等级
                unitId: '', //内设部门ID
                userRole: '', //角色ID
                permissions: [], // 按钮路径（数据库中的path）
            },
            // 按钮权限
            permissionIsShow: {
                add: false,
                edit: false,
                delete: false,
            },
        }
    },
    created() {
        const info = JSON.parse(localStorage.getItem("user"));
        this.loginUserInfo = {
            id: Number(info.id),
            responsibleScope: info.responsibleScope, //查询范围
            roleLevel: Number(info.roleLevel),
            unitId: Number(info.unitId),
            userRole: Number(info.userRole),
            permissions: info.permissions.filter(item => Number(item.menuId) === 32).map(item => item.path),
        }
        this.permissionIsShow = {
            add: this.loginUserInfo.permissions.includes('term-add'),
            edit: this.loginUserInfo.permissions.includes('term-edit'),
            delete: this.loginUserInfo.permissions.includes('term-delete'),
        }
        this.load()
    },
    computed: {
        // 获取所有唯一的法律类型
        uniquelawTypes() {
            return [...new Set(this.lowsList.map(low => low.type))];
        },
    },
    methods: {
        // 获取数据
        load() {
            this.gettableData()
            this.getLowsList()
        },
        // 搜索
        searchTerms() {
            this.pageNum = 1;
            this.gettableData();
        },

        // 分页
        handleSizeChange(val) {
            this.pageSize = val;
            this.gettableData();
        },
        handleCurrentChange(val) {
            this.pageNum = val;
            this.gettableData();
        },

        // 查询数据
        gettableData() {
            request.get("/term/page", {
                params: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    lawType: this.searchLawType,
                    lawName: this.searchLawName,
                    article: this.searchArticle,
                    paragraph: this.searchParagraph,
                    subparagraph: this.searchSubparagraph,
                    item: this.searchItem,
                }
            }).then(res => {
                if (res.code == '200') {
                    this.TermsList = res.data.records
                    this.total = res.data.total
                }
            })
        },
        // 获取法律列表数据
        getLowsList() {
            request.get("/laws/all").then(res => {
                if (res.code == '200') {
                    this.lowsList = res.data
                }
            })
        },
        // 获取第几条数据
        getArticleList(item) {
            request.get("/term/getLevelData", {
                params: {
                    level: 1,
                    lowsId: item.lawsId,
                }
            }).then(res => {
                if (res.code == '200') {
                    this.articleList = res.data.dataList
                }
            })
        },
        // 获取第几款数据
        getParagraphList(item) {
            request.get("/term/getLevelData", {
                params: {
                    level: 2,
                    lowsId: item.lawsId,
                    article: item.article,
                }
            }).then(res => {
                if (res.code == '200') {
                    this.paragraphList = res.data.dataList
                    if (res.data.id !== null) {
                        item.id = res.data.id;
                        item.content = res.data.content;
                    }
                }
            })
        },
        // 获取第几项数据
        getSubparagraphList(item) {
            request.get("/term/getLevelData", {
                params: {
                    level: 3,
                    lowsId: item.lawsId,
                    article: item.article,
                    paragraph: item.paragraph,
                }
            }).then(res => {
                if (res.code == '200') {
                    this.subparagraphList = res.data.dataList
                    if (res.data.id !== null) {
                        item.id = res.data.id;
                        item.content = res.data.content;
                    }
                }
            })
        },
        // 获取第几目数据
        getItemList(item) {
            request.get("/term/getLevelData", {
                params: {
                    level: 4,
                    lowsId: item.lawsId,
                    article: item.article,
                    paragraph: item.paragraph,
                    subparagraph: item.subparagraph,
                }
            }).then(res => {
                if (res.code == '200') {
                    this.itemList = res.data.dataList
                    if (res.data.id !== null) {
                        item.id = res.data.id;
                        item.content = res.data.content;
                    }
                }
            })
        },
        clearLawsFields(item, level) {
            if (level === "type") {
                item.lawType = null;
            }
            item.lawName = null;
            item.lawsId = null;
            // 清空依赖字段
            this.clearDependentFields(item, 1);
        },
        // 清空依赖字段
        clearDependentFields(item, level) {
            // level表示从哪一级开始清空（1=条，2=款，3=项，4=目）
            if (level <= 1) {
                item.article = null;
            }
            if (level <= 2) {
                item.paragraph = null;
            }
            if (level <= 3) {
                item.subparagraph = null;
            }
            if (level <= 4) {
                item.item = null;
            }
            item.content = null;
            item.id = null;
        },

        // 过滤法规名称
        filteredLowsByType(type) {
            // 按类型过滤
            let filtered = this.lowsList;
            if (type) {
                filtered = filtered.filter(low => low.type === type);
            }
            return filtered;
        },

        // 处理法律类型变化（下拉选择时触发）
        handlelawTypeChange(item, val) {
            item.lawType = val; // 更新类型
        },

        // 处理法律类型输入（失去焦点时触发）
        handlelawTypeBlur(item, event) {
            item.lawType = event.target.value;
            item.lawName = null;
            item.lawsId = null;
            this.clearDependentFields(item, 1);
        },

        // 处理法律名称变化（下拉选择时触发）
        handlelawNameChange(item, val) {
            item.lawName = val; // 更新名称
            // 如果是从下拉框选择的，找到对应的法律ID
            if (val) {
                const selectedLaw = this.lowsList.find(
                    law => law.name === val && law.type === item.lawType
                );
                item.lawsId = selectedLaw ? selectedLaw.id : null;
            }
        },

        // 处理法律名称输入（失去焦点时触发）
        handlelawNameBlur(item, event) {
            // 只有当是通过输入而不是选择时才处理
            if (event.target.value) {
                const isExisting = this.lowsList.some(
                    law => law.name === event.target.value && law.type === item.lawType
                );
                if (!isExisting) {
                    item.lawName = event.target.value;
                    item.lawsId = null; // 手动输入时，清空ID
                } else {
                    this.lowsList.forEach(low => {
                        if (low.name === event.target.value && low.type === item.lawType) {
                            item.lawsId = low.id;
                            item.lawName = low.name;
                        }
                    })
                }
                this.clearDependentFields(item, 1);
                // this.getArticleList(item)
            }
        },

        /*
        // 处理第几条变化（下拉选择时触发）
        handleArticleChange(item, val) {
            item.article = val; // 更新名称
            if (val) {
                const selectedArticle = this.articleList.find(
                    article => article === val
                );
                item.article = selectedArticle ? selectedArticle : null;
            }
        },

        // 处理第几条输入（失去焦点时触发）
        handleArticleBlur(item, event) {
            // 只有当是通过输入而不是选择时才处理
            if (event.target.value) {
                const isExisting = this.articleList.some(
                    article => article === event.target.value
                );
                if (!isExisting) {
                    item.article = event.target.value;
                } else {
                    this.articleList.forEach(article => {
                        if (article === event.target.value) {
                            item.article = article;
                        }
                    })
                }
                this.clearDependentFields(item, 2);
                this.getParagraphList(item)
            }
        },

        // 处理第几款变化（下拉选择时触发）
        handleParagraphChange(item, val) {
            item.paragraph = val; // 更新名称
            if (val) {
                const selectedParagraph = this.paragraphList.find(
                    paragraph => paragraph === val
                );
                item.paragraph = selectedParagraph ? selectedParagraph : null;
            }
        },

        // 处理第几款输入（失去焦点时触发）
        handleParagraphBlur(item, event) {
            // 只有当是通过输入而不是选择时才处理
            if (event.target.value) {
                const isExisting = this.paragraphList.some(
                    paragraph => paragraph === event.target.value
                );
                if (!isExisting) {
                    item.paragraph = event.target.value;
                } else {
                    this.paragraphList.forEach(paragraph => {
                        if (paragraph === event.target.value) {
                            item.paragraph = paragraph;
                        }
                    })
                }
                this.clearDependentFields(item, 3);
                this.getSubparagraphList(item)
            }
        },

        // 处理第几项变化（下拉选择时触发）
        handleSubparagraphChange(item, val) {
            item.subparagraph = val; // 更新名称
            if (val) {
                const selectedSubparagraph = this.subparagraphList.find(
                    subparagraph => subparagraph === val
                );
                item.subparagraph = selectedSubparagraph ? selectedSubparagraph : null;
            }
        },

        // 处理第几项输入（失去焦点时触发）
        handleSubparagraphBlur(item, event) {
            // 只有当是通过输入而不是选择时才处理
            if (event.target.value) {
                const isExisting = this.subparagraphList.some(
                    subparagraph => subparagraph === event.target.value
                );
                if (!isExisting) {
                    item.subparagraph = event.target.value;
                } else {
                    this.subparagraphList.forEach(subparagraph => {
                        if (subparagraph === event.target.value) {
                            item.subparagraph = subparagraph;
                        }
                    })
                }
                this.clearDependentFields(item, 4);
                this.getItemList(item)
            }
        },
        // 处理第几目变化（下拉选择时触发）
        handleItemChange(it, val) {
            if (val) {
                const selectedItem = this.itemList.find(
                    item => item === val
                );
                let item = selectedItem ? selectedItem : null;
                if (item !== null) {
                    it.item = item.item ? item.item : null;
                    it.content = item.content ? item.content : null;
                    it.id = item.id ? item.id : null;
                }
            }
        },

        // 处理第几目输入（失去焦点时触发）
        handleItemBlur(it, event) {
            // 只有当是通过输入而不是选择时才处理
            if (event.target.value) {
                const isExisting = this.itemList.some(
                    item => item.item === event.target.value
                );
                if (!isExisting) {
                    it.item = event.target.value;
                    it.content = null;
                    it.id = null;
                } else {
                    this.itemList.forEach(item => {
                        if (item.item === event.target.value) {
                            it.item = item.item ? item.item : null;
                            it.content = item.content ? item.content : null;
                            it.id = item.id ? item.id : null;
                        }
                    })
                }
            }
        }, */

        // 新增法规
        addTerms() {
            this.isEdit = false
            this.dialogFormVisible = true
        },
        // 新增弹窗关闭
        closeAddTerms() {
            this.dialogFormVisible = false
            this.inputTermsObject = {
                id: null,
                lawsId: null, // 法律ID
                article: null, // 第几条
                paragraph: null, // 第几款
                subparagraph: null, // 第几项
                item: null, // 第几目
                lawName: null, // 法律名称
                lawType: null, // 法律类型
                content: null, // 条款内容
            }
        },
        // 验证表单
        isValidate(form) {
            // 定义规则
            const rules = {
                lawType: [{ required: true, message: '请输入法律类型', trigger: 'change' }],
                lawName: [{ required: true, message: '请输入法律名称', trigger: 'blur' }],
                article: [{ required: true, message: '请输入第几条', trigger: 'blur' }],
                content: [{ required: true, message: '请输入条款内容', trigger: 'blur' }],
            }
            // 验证表单
            for (const key in rules) {
                if (rules.hasOwnProperty(key)) {
                    const rule = rules[key];
                    const value = form[key];
                    if (!value) {
                        this.$message({
                            message: rule[0].message,
                            type: 'warning'
                        })
                        return false;
                    }
                }
            }
            return true;
        },

        saveTerms() {
            console.log(this.inputTermsObject)

            // 验证表单
            if (!this.isValidate(this.inputTermsObject)) {
                return
            }

            // 向后端传输数据
            request.post('/term/edit', this.inputTermsObject).then(res => {
                if (res.code === '200' && res.data === true) {
                    this.$message({
                        message: '保存成功',
                        type: 'success'
                    })
                    this.closeAddTerms()
                    // 更新数据
                    this.load()
                } else if (res.code === '500') {
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    })
                } else {
                    this.$message({
                        message: '保存失败',
                        type: 'error'
                    })
                }
            })
        },
        // 删除
        async deleteRoleData(id) {
            const response = await request.get(`/term/deleteBeforeVerify`, {
                params: {
                    id: id
                }
            })
            let actNum = 0
            if (response.code === '200') {
                actNum = response.data
            }

            this.$confirm(actNum > 0 ? `有${actNum}条违法行为在使用该条款，是否强制删除？` : '确定删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get(`/term/delete/${id}`).then(res => {
                    if (res.code === '200') {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        // 更新数据
                        this.load()
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    message: '已取消删除',
                    type: 'info'
                })
            })
        },
        // 编辑法规
        editRoleData(row) {
            this.isEdit = true;
            this.inputTermsObject = { ...row };
            this.dialogFormVisible = true
        },

        // 判断第几条是否可编辑
        isArticleEditable(item) {
            if (!item.lawName) {
                return true
            }
            return false
        },

        // 判断第几款是否可编辑
        isParagraphEditable(item) {
            if (!item.article) {
                return true
            }
            return false
        },
        // 判断第几项是否可编辑
        isSubparagraphEditable(item) {
            if (!item.paragraph) {
                return true
            }
            return false
        },
        // 判断第几目是否可编辑
        isItemEditable(item) {
            if (!item.subparagraph) {
                return true
            }
            return false
        },
        // 判断内容是否可编辑
        isContentEditable(item) {
            if (!item.article) {
                return true
            }
            return false
        }
    }
}
</script>

<style scoped>
#roleSpan {
    color: black;
    text-decoration: none;
}

/*   外框架   */
.framework1 {
    height: calc(100vh - 88px);
    width: calc(100vh - 200px);
    margin-left: 8px;
    border: solid 1px #D3D3D3;
}

/*   内框架   */
.framework2 {
    height: calc(100vh - 92px);
    border: solid 1px #D3D3D3;
}

/*   表格大标题   */
.header {
    font-size: 16px;
    font-weight: bold;
    padding: 4px 20px;
    background-color: #D3D3D3;
}

/*   表格按键组   */
.button_group {
    padding: 4px 10px;
    background-color: #DDDDDD;
}

/*   表格分页处   */
.footer {
    padding: 4px 10px;
    background-color: #f4f3f9;
}


.formatted-text {
    text-align: left;
    white-space: pre-wrap;
}
</style>
